package com.itheima.system.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.system.dao.UserMapper;
import com.itheima.system.pojo.User;
import com.itheima.system.service.UserService;

import com.itheima.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询所有
     * @return
     */
    @Override
    public List<User> findAll() {
        return userMapper.selectAll();
    }

    /**
     * 删除用户
     * @param id
     */
    @Override
    public void delete(Long id) {
        User user = userMapper.selectByPrimaryKey(id);
        user.setStatus("1");
        userMapper.updateByPrimaryKey(user);
    }


    /**
     *修改密码
     * @param user
     */
    @Override
    public void updatePassword(User user) {
        Long id = user.getId();

        userMapper.updateByPrimaryKey(user);
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<User> findPage(int page, int size){
        PageHelper.startPage(page,size);
        return (Page<User>)userMapper.selectAll();
    }

    /**
     * 添加用户
     * @param user
     */
    @Override
    public void add(User user) {
        user.setStatus("1");
        String s = MD5Util.inputPassToFormPass("123456");
        user.setPassword(s);
        userMapper.insertSelective(user);
    }

    /**
     * 添加用户角色关联
     * @param user
     * @param roleIds
     */
    @Override
    public void addUserAndRole(User user, Long[] roleIds) {
        user.setStatus("1");
        String password = user.getPassword();
        String s = MD5Util.inputPassToFormPass(password);
        user.setPassword(s);
        userMapper.insertSelective(user);
        Long userId = user.getId();
        this.setUserAndRole(userId,roleIds);
    }

    /**
     * 登录
     * @param user
     * @return
     */
    @Override
    public User findUserNameAndPassWord(User user) {
        if (!redisTemplate.opsForHash().hasKey("redisCount", user.getUsername())) {
            //如果不存在,就将count的值设为0
            int count = 0;
            redisTemplate.opsForHash().put("redisCount", user.getUsername(), count);
        }
        //将redisCount取出来
        int redisCount = (int) redisTemplate.boundHashOps("redisCount").get(user.getUsername());
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", user.getUsername());
        criteria.andEqualTo("password", MD5Util.inputPassToFormPass(user.getPassword()));

        User User = userMapper.findByUserNameAndPssword(user);
        User Users = userMapper.selectOneByExample(example);//登录的user
        if (Users == null) {
            redisCount++;
            redisTemplate.opsForHash().put("redisCount", user.getUsername(), redisCount);
            //当用户输错五次的时候,就锁定他的账号,把状态值从1改成0,0:表示停用,1:表示启用
            if (redisCount >= 5) {
                User.setStatus("0");
                userMapper.updateByPrimaryKeySelective(User);
            }
            throw new RuntimeException("用户名或者密码错误");
        }
        //如果用户成功
        redisTemplate.opsForHash().delete("redisCount", "username", redisCount);
        User.setStatus("1");
        userMapper.updateByPrimaryKeySelective(User);

        return Users;
    }

    private void setUserAndRole(Long userId, Long[] roleIds) {
        if (userId != null && roleIds.length>0){
            for (Long roleId : roleIds) {
                Map<String, Long> map = new HashMap<>();
                map.put("userId",userId);
                map.put("roleId",roleId);
                userMapper.setUserAndRole(map);
            }
        }
    }
}
